package com.controller.backend;

import com.biz.ManagerInfoBiz;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.model.ManagerInfo;
import com.util.AESUtil;
import com.util.SystemConstant;
import com.util.VerifyCodeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Condition;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by Administrator on 2017-09-15.
 */
@Controller
public class LoginController {

    @Autowired
    private ManagerInfoBiz managerInfoBiz;

    //登录页面
    @RequestMapping(value = "/backend/loginIndex")
    public void toLogin(HttpSession session, HttpServletResponse response, Integer mod, String sign) throws Exception {
        //poenBrowser("https://superbrain.51gugua.com/cms/index.aspx");
        if (mod != null && mod == 1) {
            String str = AESUtil.decrypt(sign);
            if (str.split("\\|")[3].equals("gugua")) {
                String id = str.split("\\|")[0];
                String account = str.split("\\|")[1];
                String userName = str.split("\\|")[1];

                ManagerInfo managerInfo = managerInfoBiz.findById(Integer.valueOf(id));
                if (managerInfo != null) {
                    session.removeAttribute(SystemConstant.SESSION_SECURITY_CODE);
                    session.setAttribute(SystemConstant.SESSION_ADMIN, managerInfo);
                    session.setMaxInactiveInterval(3600 * 24 * 30);

                    response.sendRedirect("https://dmshotel.51gugua.com/backend/security/index");
                } else {
                    managerInfo = new ManagerInfo();
                    managerInfo.setId(Integer.valueOf(id));
                    managerInfo.setUserName(userName);
                    managerInfo.setAccount(account);
                    managerInfo.setPassword(DigestUtils.md5Hex(account + "123456"));
                    managerInfoBiz.save(managerInfo);

                    session.removeAttribute(SystemConstant.SESSION_SECURITY_CODE);
                    session.setAttribute(SystemConstant.SESSION_ADMIN, managerInfo);
                    session.setMaxInactiveInterval(3600 * 24 * 30);

                    response.sendRedirect("https://dmshotel.51gugua.com/backend/security/index");
                }
            }
        } else {
            response.sendRedirect("https://superbrain.51gugua.com/cms/index.aspx");
        }
        //return "/backend/login";
    }

    //登录验证
    @RequestMapping(value = "/backend/loginCheck", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result loginCheck(HttpSession session, @RequestParam String account, @RequestParam String password, @RequestParam String verifyCode) throws Exception {
        if (StringUtils.isBlank(account)) {
            return ResultGenerator.genFailResult("账号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return ResultGenerator.genFailResult("密码不能为空");
        }
        String code = (String) session.getAttribute(SystemConstant.SESSION_SECURITY_CODE);
        if (!verifyCode.equals(code)) {
            return ResultGenerator.genFailResult("验证码错误");
        }
        Condition cond = new Condition(ManagerInfo.class);
        password = DigestUtils.md5Hex(account + password);
        cond.createCriteria().andEqualTo("account", account).andEqualTo("password", password);
        List<ManagerInfo> list = managerInfoBiz.findByCondition(cond);
        session.removeAttribute(SystemConstant.SESSION_SECURITY_CODE);
        if (list.size() == 0) {
            return ResultGenerator.genFailResult(-99, "账号或密码错误");
        }
        session.setAttribute(SystemConstant.SESSION_ADMIN, list.get(0));
        session.setMaxInactiveInterval(3600 * 24 * 30);
        return ResultGenerator.genSuccessResult("/backend/security/index");
    }

    //退出登录
    @RequestMapping("/backend/security/loginOut")
    @ResponseBody
    public Result logout(HttpSession session) {
        session.invalidate();
        return ResultGenerator.genSuccessResult("/backend/loginIndex");
    }

    @RequestMapping(value = "/backend/captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request) {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //为了手机客户端方便使用数字验证码
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
        HttpSession session = request.getSession();
        session.setAttribute(SystemConstant.SESSION_SECURITY_CODE, verifyCode);
        try {
            //设置输出的内容的类型为JPEG图像
            response.setContentType("image/jpeg");
            BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null, null);
            //写给浏览器
            ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void poenBrowser(String url) throws Exception {
        // 获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {
            // 苹果的打开方式
            Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
            openURL.invoke(null, new Object[]{url});
        } else if (osName.startsWith("Windows")) {
            // windows的打开方式。
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else {
            // Unix or Linux的打开方式
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++)
                // 执行代码，在brower有值后跳出，
                // 这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
                    browser = browsers[count];
                }
            if (browser == null) {
                throw new Exception("Could not find web browser");
            } else {
                // 这个值在上面已经成功的得到了一个进程。
                Runtime.getRuntime().exec(new String[]{browser, url});
            }
        }
    }

}
